﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ThresholdAssistant.Autofac;
using ThresholdAssistant.DataContract.Result;
using ThresholdAssistant.Tools.Extensions;
using ThresholdAssistant.WebAPI.Models;
using ThresholdAssistant.WebAPI.Repository;

namespace ThresholdAssistant.WebAPI.Service
{
    /// <summary>
    /// 标签服务
    /// </summary>
    public class TagService : BaseService, IBaseAutofac
    {
        /// <summary>
        /// 标签仓储
        /// </summary>
        public TagRepository TagRepository { get; set; }

        /// <summary>
        /// 标签类型仓储
        /// </summary>
        public TagtypeRepository TagtypeRepository { get; set; }

        /// <summary>
        /// 数据仓储
        /// </summary>
        public RecordRepository RecordRepository { get; set; }

        /// <summary>
        /// 获取标签类型列表
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<ContractResult<IEnumerable<TagtypeData>>> GetTagtypeListAsync(GetTagListParam param)
        {
            var result = new ContractResult<IEnumerable<TagtypeData>>();
            var tagtypeList = await TagtypeRepository.GetListAsync(param.GroupId);
            result.Data = tagtypeList?.Select(x => new TagtypeData
            {
                GroupId = x.GroupId,
                Id = x.Id,
                Name = x.Name
            })?.ToList();
            return result.SetSuceccful(result.Data);
        }

        /// <summary>
        /// 获取标签类型列表
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<ContractResult<long>> AddTagtypeAsync(AddTagtypeParam param)
        {
            var result = new ContractResult<long>();
            var id = await TagtypeRepository.AddAsync(new Tagtype
            {
                GroupId = param.GroupId,
                Name = param.Name,
                CreateId = param.MemberId,
                CreateTime = DateTime.Now,
                UpdateTime = DateTime.Now,
                Remark = ""
            });
            result.Data = id;
            return result.SetSuceccful();
        }

        /// <summary>
        /// 获取标签类型信息
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<ContractResult<TagtypeData>> GetTagTypeInfoAsync(GetTagtypeInfoParam param)
        {
            var result = new ContractResult<TagtypeData>();
            var tagInfo = await TagtypeRepository.GetInfoAsync(param.Id);
            result.Data = new TagtypeData
            {
                GroupId = tagInfo?.GroupId ?? 0,
                Id = tagInfo?.Id ?? 0,
                Name = tagInfo?.Name ?? "",
            };
            return result.SetSuceccful();
        }


        /// <summary>
        /// 删除标签类型下的数据
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<ContractResult> DeleteTagtypeAsync(DeleteTagtypeParam param)
        {
            var result = new ContractResult();
            await TagtypeRepository.DeleteAsync(param.Id);

            // 删除标签类型后，删除对应的标签
            var tagIdList = await TagRepository.GetListAsync(param.Id);
            if (tagIdList?.Any() == true)
            {
                await TagRepository.DeleteAsync(tagIdList);

                // 删除标签对应的数据
                await RecordRepository.DeletesByTagIdsAsync(tagIdList);
            }

            return result.SetSuceccful();
        }

        /// <summary>
        /// 修改标签类型
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<ContractResult> UpdateTagtypeAsync(UpdateTagtypeParam param)
        {
            var result = new ContractResult();
            var tagtypeInfo = await TagtypeRepository.GetInfoAsync(param.Id);
            if (tagtypeInfo != null)
            {
                tagtypeInfo.Name = param.Name;
                tagtypeInfo.UpdateTime = DateTime.Now;
                await TagtypeRepository.UpdateAsync(tagtypeInfo);
            }
            return result.SetSuceccful();
        }

        /// <summary>
        /// 获取标签列表
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<ContractResult<IEnumerable<TagData>>> GetTagListAsync(GetTagListParam param)
        {
            var result = new ContractResult<IEnumerable<TagData>>();
            var tagList = await TagRepository.GetListAsync(param.GroupId, param.TagtypeId);
            result.Data = tagList?.Select(x => new TagData
            {
                Id = x.Id,
                GroupId = x.GroupId,
                TagtypeId = x.TagtypeId,
                Name = x.Name
            })?.ToList();
            return result.SetSuceccful(result.Data);
        }

        /// <summary>
        /// 新增标签
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<ContractResult<long>> AddTagAsync(AddTagParam param)
        {
            //todo 判断标签类型是否存在
            var result = new ContractResult<long>();
            var id = await TagRepository.AddAsync(new Tag
            {
                GroupId = param.GroupId,
                Name = param.Name,
                TagtypeId = param.TagtypeId,
                CreateId = param.MemberId,
                CreateTime = DateTime.Now,
                UpdateTime = DateTime.Now,
                Remark = ""
            });
            result.Data = id;
            return result.SetSuceccful();
        }

        /// <summary>
        /// 获取标签信息
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<ContractResult<TagData>> GetTagInfoAsync(GetTagInfoParam param)
        {
            var result = new ContractResult<TagData>();
            var tagInfo = await TagRepository.GetInfoAsync(param.Id);
            result.Data = new TagData
            {
                Id = tagInfo?.Id ?? 0,
                GroupId = tagInfo?.GroupId ?? 0,
                TagtypeId = tagInfo?.TagtypeId ?? 0,
                Name = tagInfo?.Name ?? "",
            };
            return result.SetSuceccful();
        }

        /// <summary>
        /// 删除标签下的数据
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<ContractResult> DeleteTagAsync(DeleteTagParam param)
        {
            var result = new ContractResult();
            var tagIdList = new List<long> { param.Id };
            await TagRepository.DeleteAsync(tagIdList);

            // 删除标签对应的数据
            await RecordRepository.DeletesByTagIdsAsync(tagIdList);

            return result.SetSuceccful();
        }

        /// <summary>
        /// 修改标签信息
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<ContractResult> UpdateTagAsync(UpdateTagParam param)
        {
            var result = new ContractResult();
            var tagInfo = await TagRepository.GetInfoAsync(param.Id);
            if (tagInfo != null)
            {
                tagInfo.Name = param.Name;
                tagInfo.TagtypeId = param.TagtypeId;
                tagInfo.UpdateTime = DateTime.Now;
                await TagRepository.UpdateAsync(tagInfo);
            }
            return result.SetSuceccful();
        }

        /// <summary>
        /// 获取标签列表
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<ContractResult<IEnumerable<object>>> GetTagDtoListAsync(GetTagListParam param)
        {
            var result = new ContractResult<IEnumerable<object>>();

            var tagList = await TagRepository.GetListByGroupIdAsync(param.GroupId);
            var records = tagList?.Select(x => new TagData
            {
                Id = x.Id,
                GroupId = x.GroupId,
                TagtypeId = x.TagtypeId,
                Name = x.Name
            })?.ToList();
            if (records == null || records.Any() == false)
                return result;

            var list = new List<object>();
            var tagTypeIds = records.Select(x => x.TagtypeId).Distinct().OrderBy(x => x).ToList();
            var tagTypes = await TagtypeRepository.GetListByIdsAsync(tagTypeIds);
            var _list = new List<Tagtype>();
            foreach (var tagTypeId in tagTypeIds)
            {
                _list = tagTypes.Where(x => x.Id == tagTypeId).ToList();
                list.Add(new
                {
                    label = _list[0].Name,
                    value = tagTypeId.ToString(),
                    children = records.Where(x => x.TagtypeId == tagTypeId).Select(x => new { label = x.Name, value = x.Id.ToString() })
                });
            }

            result.Data = list;
            return result.SetSuceccful(result.Data);
        }
    }
}